(function($){
	$.fn.livesearch = function(mode) {


 		return this.each(function() {
 			var select = this;
 			var search = $('<input type="text"/>').attr('class', 'livesearch-search');
 			search.attr('placeholder', $(select).attr('data-placeholder'));
 			var results = $('<ul/>').attr('class', 'livesearch-search-results').css('display', 'none');
 			if(mode == 'multiple') {
				var ul = $('<ul/>').attr('class', 'livesearch-selections');
			}
			else {
				$(select).prepend('<option value=""></option>');
			}
			var clearBoth = $('<div/>').css('clear', 'both');
			$(this).after(search);
			search.after(results);
			
			
			clearBoth.after(results);
			if(mode == 'multiple') {
				search.before(ul);
				ul.data('select', select);
				$(this).children('option:selected').each(function() {
					if($(this).val()) {
						var child = $('<li/>').data('option', this).html($(this).html() + '<a class="remove-livesearch" href="javascript:void();">X</a>').appendTo(ul);
						child.children('.remove-livesearch').click(function() {
							var parent = $(this).parent('li');
							$(parent.data('option')).attr('selected', false);
				
							parent.remove();
						});
					}
				});
			}
			else {
				if($(this).children('option:selected').length) {
					search.val($(this).children('option:selected').html()).css('font-style', '').css('color', '').css('font-weight', 'bold');
				}
			}
			
			$(this).hide();
			search.keyup(function() {
				results.html('');
				var query = $(this).val();
				if(mode != 'multiple') {
					$(select).val('');
				}
				if(query) {
					results.show();
					var i = 0;
					if(mode == 'multiple') {
						$(select).find(":contains('" + query + "')").not(':selected').each(function() {
							if(i<10) {
								var child = $('<li/>').html($(this).html()).appendTo(results);
								child.data('option', this);
								child.click(function() {
									var append = $('<li/>').html($(this).html() + '<a class="remove-livesearch" href="javascript:void();">X</a>').appendTo(ul);
									append.data('option', $(this).data('option'));
									append.children('.remove-livesearch').click(function() {
										$($(this).parent('li').data('option')).attr('selected', false);
										$(this).parent('li').remove();
									});
									
									$($(this).data('option')).attr('selected', 'selected');
									$(this).remove();
									search.val('');
									results.hide();
								});
							}
							i++;
						});
					}
					else {
						$(select).find(":contains('" + query + "')").each(function() {
							if(i<10) {
								var child = $('<li/>').html($(this).html()).appendTo(results);
								child.data('option', this);
								child.click(function() {
									$($(this).data('option')).attr('selected', 'selected');
									search.val($(this).html());
									results.hide();
								});
							}
							i++;
						});
					}
				}
				else {
					results.hide();
					
				}
			
			});
		});
	};
})(jQuery);